import { reqGetCode, reqUserLogin, reqUserRegister, reqUserInfo, reqLogout } from '@/api/index'
import { setToken, getToken, removeToken } from '@/utils/token'
//登入与注册的模块
const state = {
    code: '',
    token: getToken(), //起始是空串：none
    userInfo: {},
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //清除自己本地的数据
    CLEAR(state) {
        //把仓库中相关用户信息清空。
        state.token = ''
        state.userInfo = {}
            //本地存储数据清空。
        removeToken()


    }
}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        //获取验证码这个接口，把验证码返回，但是正常情况下，，后台把验证码发到用户手机上【省钱】
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
            // console.log(result);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户登入[token]
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
            // console.log(result);
            //服务器下发的token,是用户的唯一标识[uuid]
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
                //持久化存储token
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //获取用户信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
            // console.log(result);
        if (result.code == 200) {
            commit('GETUSERINFO', result.data) //t提交用户信息
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //退出登录
    async userLogout({ commit }) {
        //只是向服务器发起一次请求，通知服务器清除token
        let result = await reqLogout()
        if (result.code == 200) {
            commit('CLEAR')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters,
}